package com.ruoyi.iot.controller;



import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.iot.feign.provide.IWxCmdFeign;
import com.ruoyi.iot.feign.provide.IWxDeviceFeign;
import com.ruoyi.iot.feign.provide.IWxProjectFeign;
import com.ruoyi.iot.domain.*;
import com.ruoyi.iot.domain.vo.DevCmdVo;
import com.ruoyi.iot.domain.vo.UserOperateVO;
import com.ruoyi.iot.domain.vo.enums.ECodeEnum;
import com.ruoyi.iot.domain.vo.enums.EPlatformCmdType;
import com.ruoyi.iot.domain.vo.enums.ESponsor;
import com.ruoyi.iot.domain.vo.weixin.element.*;
import com.ruoyi.iot.domain.vo.weixin.WxCmdVO;
import com.ruoyi.iot.domain.vo.weixin.WxDeviceVO;
import com.ruoyi.iot.domain.vo.weixin.WxProjectVO;
import com.ruoyi.iot.domain.vo.weixin.field.WxCmdFieldInnerDetail;
import com.ruoyi.iot.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@Slf4j
public class WxRequestController implements IWxCmdFeign, IWxDeviceFeign, IWxProjectFeign {

    /**
     * 项目服务
     */
    @Autowired
    IotProjectServiceImpl projectService;

    /**
     * 设备操作服务
     */
    @Autowired
    IotDeviceOperationImpl iotDeviceOperation;

    /**
     * 设备服务
     */
    @Autowired
    IotDeviceServiceImpl iotDeviceService;

    /**
     * 产品服务
     */
    @Autowired
    IotProductServiceImpl iotProductService;


    /**
     * 指令服务
     */
    @Autowired
    IotCmdServiceImpl iotCmdService;



    /**
     * 指令编码服务
     */
    @Autowired
    IotCmdEncoderServiceImpl iotCmdEncoderService;

    /**
     * 数据包字段服务
     */
    @Autowired
    IotProductFieldServiceImpl iotProductFieldService;


    /**
     * 设备指令解析模块
     */
    @Autowired
    IotCmdDecodeServiceImpl iotCmdDecodeService;



    @Override
    public AjaxResult takeWxCmdVO(Long productId) {
        IotCmd iotCmd = new IotCmd();
        iotCmd.setProductId(productId);
        iotCmd.setCmdType(EPlatformCmdType.CMD.getValue().longValue());
        iotCmd.setSponsor(ESponsor.platform.getValue());

        List<IotCmd> cmdList = iotCmdService.selectIotCmdList(iotCmd);
        WxCmdVO wxCmdVO = new WxCmdVO();
        List<WxCmdFieldDetail> wxCmdFieldDetails = new ArrayList<>();

        cmdList.forEach(item -> {
            WxCmdFieldDetail wxCmdFieldDetail = new WxCmdFieldDetail();
            wxCmdFieldDetail.setId(item.getId());
            Integer thumbLen = 24;
            if(item.getName().length() > thumbLen) {
                String thumbName = item.getName().substring(0,thumbLen);
                wxCmdFieldDetail.setName(thumbName + "...");
            } else {
                wxCmdFieldDetail.setName(item.getName());
            }

            List<WxCmdFieldInnerDetail> wxCmdFieldInnerDetails = new ArrayList<>();
            IotCmdEncoder iotCmdEncoder = new IotCmdEncoder();
            iotCmdEncoder.setCmdId(item.getId());
            List<IotCmdEncoder> cmdEncoders = iotCmdEncoderService.selectIotCmdEncoderList(iotCmdEncoder);
            //log.info("iot cmdEncoder:" + JSON.toJSONString(cmdEncoders));
            cmdEncoders.forEach(encoderItem ->{
                WxCmdFieldInnerDetail wxCmdFieldInnerDetail = new WxCmdFieldInnerDetail();
                IotProductField iotProductField = iotProductFieldService.selectIotProductFieldById(encoderItem.getFieldId());
              //  log.info("iot Product:" + JSON.toJSONString(iotProductField));
                if(iotProductField != null) {
                    wxCmdFieldInnerDetail.setFieldKey(iotProductField.getField());
                    wxCmdFieldInnerDetail.setFieldName(iotProductField.getName());
                    wxCmdFieldInnerDetail.setRemark(iotProductField.getRemark());
                    wxCmdFieldInnerDetail.setValue(iotProductField.getDefVal());
                    wxCmdFieldInnerDetails.add(wxCmdFieldInnerDetail);
                }
            });

            wxCmdFieldDetail.setWxCmdFieldInnerDetails(wxCmdFieldInnerDetails);
            wxCmdFieldDetails.add(wxCmdFieldDetail);
        });

        wxCmdVO.setWxCmdFieldDetails(wxCmdFieldDetails);
        log.info("wx cmd:" + JSON.toJSONString(wxCmdVO));
        return AjaxResult.success(wxCmdVO);
    }

    @Override
    public AjaxResult takeWxDeviceVO(String projectId) {
        WxDeviceVO wxDeviceVO = new WxDeviceVO();
        IotDevice iotDevice = new IotDevice();

        iotDevice.setProjectId(Long.parseLong(projectId));
        List<IotDevice> iotDevices = iotDeviceService.selectIotDeviceList(iotDevice);
        List<WxDeviceDetail> wxDeviceDetails = new ArrayList<>();
        Set<WxProductSegments> segmentsSet = new HashSet<>();
        iotDevices.forEach(item -> {
            WxDeviceDetail wxDeviceDetail = new WxDeviceDetail();
            wxDeviceDetail.parse(item);
            WxProductSegments wxProductSegments = new WxProductSegments();
            Long productId = item.getProductId();
            String productName = iotProductService.selectIotProductById(productId).getName();
            wxProductSegments.setName(productName);
            wxProductSegments.setProductId(productId);
            segmentsSet.add(wxProductSegments);

            wxDeviceDetails.add(wxDeviceDetail);
        });
        //项目下设备详情
        wxDeviceVO.setWxDeviceDetails(wxDeviceDetails);
        //项目下产品详情
        List<WxProductSegments> wxProductSegmentsList = new ArrayList<>(segmentsSet);
        wxDeviceVO.setWxProductSegments(wxProductSegmentsList);
        log.info("wx device:" + JSON.toJSONString(wxDeviceVO));
        return AjaxResult.success(wxDeviceVO);
    }

    @Override
    public AjaxResult takeWxCmdResult(DevCmdVo devCmdVo) {
        log.info("devCmd:" + JSON.toJSONString(devCmdVo));
        UserOperateVO<DevCmdVo> userOperateVO = iotDeviceOperation.produceUserOperate(devCmdVo);
        if(!userOperateVO.getSuccess()) {
            return AjaxResult.error(userOperateVO.getCode(),userOperateVO.getMessage());
        }
        DevCmdVo devResult = userOperateVO.getData();
        JSONObject rstJson = devResult.getData();

        List<WxCmdFieldInnerDetail> wxCmdFieldInnerDetails = new ArrayList<>();
        Long rstCmdId = devResult.getCmdId();
        if(rstCmdId == null) {
            return AjaxResult.error(ECodeEnum.RstCmdError.getCode(),ECodeEnum.RstCmdError.getMsg());
        }

        log.info("cmdId:" + rstCmdId);
        String rstCmdName = iotCmdService.selectIotCmdById(rstCmdId).getName();

        IotCmdDecode iotCmdDecode = new IotCmdDecode();
        iotCmdDecode.setCmdId(rstCmdId);
        List<IotCmdDecode> iotCmdDecodes =  iotCmdDecodeService.selectIotCmdDecodeList(iotCmdDecode);
        for(IotCmdDecode item: iotCmdDecodes) {
           Long fieldId =  item.getFieldId();
           IotProductField iotProductField =  iotProductFieldService.selectIotProductFieldById(fieldId);
            if(iotProductField != null) {
                WxCmdFieldInnerDetail wxCmdFieldInnerDetail = new WxCmdFieldInnerDetail();
                wxCmdFieldInnerDetail.setFieldKey(iotProductField.getField());
                wxCmdFieldInnerDetail.setFieldName(iotProductField.getName());
                wxCmdFieldInnerDetail.setRemark(iotProductField.getRemark());
                wxCmdFieldInnerDetail.setValue(rstJson.get(iotProductField.getField()));
                wxCmdFieldInnerDetails.add(wxCmdFieldInnerDetail);
            }
        }
        log.info("rst json:" + rstJson.toJSONString());
        log.info("rst inner" + JSON.toJSONString(wxCmdFieldInnerDetails));
        WxCmdFieldDetail wxCmdFieldDetail = new WxCmdFieldDetail();
        wxCmdFieldDetail.setId(rstCmdId);
        wxCmdFieldDetail.setWxCmdFieldInnerDetails(wxCmdFieldInnerDetails);
        wxCmdFieldDetail.setName(rstCmdName);


        return AjaxResult.success(userOperateVO.getMessage(),wxCmdFieldDetail);
    }




    @Override
    public AjaxResult takeWxProject() {
        WxProjectVO wxProjectVO = new WxProjectVO();

        List<WxProjectDetail> wxProjectDetails = new ArrayList<>();

        List<IotProject> iotProjects = projectService.selectIotProjectList(new IotProject());

        for(IotProject iotProject:iotProjects) {
            WxProjectDetail item = new WxProjectDetail();
            item.parse(iotProject);
            wxProjectDetails.add(item);
        }
        wxProjectVO.setData(wxProjectDetails);

        List<WxProjectSegments> projectSegmentsList = new ArrayList<>();
        Integer[] states = new Integer[]{1,2,3,4,5};
        String[] names = new String[]{"立项","施工","验收","竣工","完工"};
        for(int i = 0; i < states.length; i++) {
            WxProjectSegments wxProjectSegments = new WxProjectSegments();
            wxProjectSegments.setState(states[i]);
            wxProjectSegments.setName(names[i]);
            projectSegmentsList.add(wxProjectSegments);
        }

        wxProjectVO.setSegments(projectSegmentsList);

        log.info("wx project:" + JSON.toJSONString(wxProjectVO));
        return AjaxResult.success(wxProjectVO);
    }

}
